<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        /*为了能够设置两个标签叠加在一起，需要设置其父标签*/
        .father{
            /*标签位置设置为相对的*/
            position: relative;
            text-align: center;
            width: 800px;
        }
        /*canvas的大小需要在起标签内设置，否则会拉伸或缩小默认的大小*/
        .canvas{
            border:1px solid black;
            /*位置绝对*/
            position: absolute;
            top: 0;
            left: 0;
            /*设置所在层数，在上层*/
            z-index: 1;
        }
        /*需要将img背景图的尺寸和canvas的尺寸设置相同*/
        .canvas_bgp{
            width: 650px;
            height: 414px;
            /*位置绝对*/
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div>
    <canvas id="cvs" width="650px" height="414px" class="canvas" onclick="msg(event)">不支持canvas</canvas>
    <img src="http://127.0.0.1:8848/image/1594978732276.jpg"  class="canvas_bgp">
</div>
<input type="button" onclick="msg()">
<script type="text/javascript">

    var cvs = document.getElementById("cvs");
    var cvsClientRect = cvs. getBoundingClientRect();
    var points = [];

    cvs.addEventListener("mousedown", mousedownHandler, false);
    var ctx = cvs.getContext('2d');
    var flag = false;

    function mousedownHandler (event){
        if(points.length<=2){
            if(event.button == 0 && !flag) {
                points.push({
                    x: event.pageX - cvsClientRect.x,
                    y: event.pageY - cvsClientRect.y
                });
                if(points.length>=1) {
                    cvs.addEventListener("mousemove", mousemoveHandler, false);
                }
                drawPolygon(points);
                console.log(points)
            }
        }else if(event.button === 0) {
            flag = true;
            cvs.removeEventListener("mousemove", mousemoveHandler);
        }
    }

    function drawPolygon(points) {
        ctx.clearRect(0,0,650,414);

        ctx.strokeStyle = '#ff0000';
        ctx.beginPath();
        ctx.moveTo(points[0].x,points[0].y);



        for(var i=1;i<points.length;i++) {
            ctx.lineTo(points[i].x,points[i].y);
        }
        ctx.closePath();
        ctx.stroke();
        // console.log(points)


    }

    function mousemoveHandler(event) {
        drawPolygon(points.concat({
            x: event.pageX - cvsClientRect.x,
            y: event.pageY - cvsClientRect.y
        }));

    }

    function msg() {
        alert(points)
    }
</script>
</body>
</html>